// 轮播图功能
let currentSlide = 0;
const slides = document.querySelectorAll('.carousel-slide');
const dots = document.querySelectorAll('.carousel-dot');

function showSlide(n) {
    slides.forEach(slide => slide.classList.remove('active'));
    dots.forEach(dot => dot.classList.remove('active'));

    currentSlide = (n + slides.length) % slides.length;
    slides[currentSlide].classList.add('active');
    dots[currentSlide].classList.add('active');
}

// 自动轮播
setInterval(() => {
    showSlide(currentSlide + 1);
}, 5000);

// 点击小圆点切换
dots.forEach((dot, index) => {
    dot.addEventListener('click', () => {
        showSlide(index);
    });
});


// 动态生成推荐频道卡片
function renderRecommendedChannels() {
    const container = document.getElementById('channel-list');
    if (!container || !suggestChannel) return;

    // 清空容器
    container.innerHTML = '';

    const channels=suggestChannel;

    channels.forEach(channel => {
        // 检查用户是否已加入该频道
        const isJoined = addedChannel.includes(channel.cId);

        // 创建频道卡片
        const card = document.createElement('div');
        card.className = isJoined ? 'channel-card joined-channel' : 'channel-card';

        // 格式化成员数
        let memberText = channel.member;
        if (channel.member >= 10000) {
            memberText = (channel.member / 10000).toFixed(1) + '万';
        }

        // 根据是否已加入设置按钮状态
        let buttonHTML;
        if (isJoined) {
            buttonHTML = `<button class="join-button joined" data-cid="${channel.cId}" disabled><i class="fas fa-check"></i> 已加入</button>`;
        } else {
            buttonHTML = `<button class="join-button" data-cid="${channel.cId}"><i class="fas fa-plus"></i> 加入频道</button>`;
        }

        card.innerHTML = `
            <div class="channel-banner" style="background-image: url('${channel.cAvatar}');">
                <div class="channel-tag">${channel.sort}</div>
            </div>
            <div class="channel-info">
                <div class="channel-title">
                    ${channel.name}
                </div>
                <div class="channel-description">${channel.description}</div>
                <div class="channel-meta">
                    <span class="channel-members"><i class="fas fa-users"></i> ${memberText}成员</span>
                    <span class="channel-activity">
                        <span class="activity-indicator"></span> 活跃中
                    </span>
                </div>
                ${buttonHTML}
            </div>
        `;

        container.appendChild(card);
    });
}

function renderSortChannels(channels) {
    const container = document.getElementById('channel-list2');
    if (!container) return;
    container.innerHTML = '';

    channels.forEach(channel => {
        // 检查用户是否已加入该频道
        const isJoined = addedChannel.includes(channel.cId);

        // 创建频道卡片
        const card = document.createElement('div');
        card.className = isJoined ? 'channel-card joined-channel' : 'channel-card';

        // 格式化成员数
        let memberText = channel.member;
        if (channel.member >= 10000) {
            memberText = (channel.member / 10000).toFixed(1) + '万';
        }

        // 根据是否已加入设置按钮状态
        let buttonHTML;
        if (isJoined) {
            buttonHTML = `<button class="join-button joined" data-cid="${channel.cId}" disabled><i class="fas fa-check"></i> 已加入</button>`;
        } else {
            buttonHTML = `<button class="join-button" data-cid="${channel.cId}"><i class="fas fa-plus"></i> 加入频道</button>`;
        }

        card.innerHTML = `
            <div class="channel-banner" style="background-image: url('${channel.cAvatar}');">
                <div class="channel-tag">${channel.sort}</div>
            </div>
            <div class="channel-info">
                <div class="channel-title">
                    ${channel.name}
                </div>
                <div class="channel-description">${channel.description}</div>
                <div class="channel-meta">
                    <span class="channel-members"><i class="fas fa-users"></i> ${memberText}成员</span>
                    <span class="channel-activity">
                        <span class="activity-indicator"></span> 活跃中
                    </span>
                </div>
                ${buttonHTML}
            </div>
        `;

        container.appendChild(card);
    });
}

// 为分类按钮添加点击事件
function setupCategoryButtons() {
    const categoryButtons = document.querySelectorAll('.secondary-nav .nav-item[data-sort]');

    categoryButtons.forEach(button => {
        button.addEventListener('click', async function() {
            // 更新按钮激活状态
            categoryButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            const sort = this.getAttribute('data-sort');
            try {
                const response = await fetch(contextPath + `/User/findChannel?sort=${sort}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                const data = await response.json();
                renderSortChannels(data);
            } catch (error) {
                console.error('获取分类频道失败:', error);
            }
        });
    });
}

// 动态生成推荐频道卡片
function renderLoveChannels() {
    const container = document.getElementById('channel-list3');
    if (!container || !loveChannel) return;

    // 清空容器
    container.innerHTML = '';

    const channels=loveChannel;

    channels.forEach(channel => {
        // 检查用户是否已加入该频道
        const isJoined = addedChannel.includes(channel.cId);

        // 创建频道卡片
        const card = document.createElement('div');
        card.className = isJoined ? 'channel-card joined-channel' : 'channel-card';

        // 格式化成员数
        let memberText = channel.member;
        if (channel.member >= 10000) {
            memberText = (channel.member / 10000).toFixed(1) + '万';
        }

        // 根据是否已加入设置按钮状态
        let buttonHTML;
        if (isJoined) {
            buttonHTML = `<button class="join-button joined" data-cid="${channel.cId}" disabled><i class="fas fa-check"></i> 已加入</button>`;
        } else {
            buttonHTML = `<button class="join-button" data-cid="${channel.cId}"><i class="fas fa-plus"></i> 加入频道</button>`;
        }

        card.innerHTML = `
            <div class="channel-banner" style="background-image: url('${channel.cAvatar}');">
                <div class="channel-tag">${channel.sort}</div>
            </div>
            <div class="channel-info">
                <div class="channel-title">
                    ${channel.name}
                </div>
                <div class="channel-description">${channel.description}</div>
                <div class="channel-meta">
                    <span class="channel-members"><i class="fas fa-users"></i> ${memberText}成员</span>
                    <span class="channel-activity">
                        <span class="activity-indicator"></span> 活跃中
                    </span>
                </div>
                ${buttonHTML}
            </div>
        `;

        container.appendChild(card);
    });
}

function renderSearchChannels(channels) {
    const container = document.getElementById('channel-list4');
    if (!container) return;

    container.innerHTML = '';

    channels.forEach(channel => {
        // 检查用户是否已加入该频道
        const isJoined = addedChannel.includes(channel.cId);

        // 创建频道卡片
        const card = document.createElement('div');
        card.className = isJoined ? 'channel-card joined-channel' : 'channel-card';

        // 格式化成员数
        let memberText = channel.member;
        if (channel.member >= 10000) {
            memberText = (channel.member / 10000).toFixed(1) + '万';
        }

        // 根据是否已加入设置按钮状态
        let buttonHTML;
        if (isJoined) {
            buttonHTML = `<button class="join-button joined" data-cid="${channel.cId}" disabled><i class="fas fa-check"></i> 已加入</button>`;
        } else {
            buttonHTML = `<button class="join-button" data-cid="${channel.cId}"><i class="fas fa-plus"></i> 加入频道</button>`;
        }

        card.innerHTML = `
            <div class="channel-banner" style="background-image: url('${channel.cAvatar}');">
                <div class="channel-tag">${channel.sort}</div>
            </div>
            <div class="channel-info">
                <div class="channel-title">
                    ${channel.name}
                </div>
                <div class="channel-description">${channel.description}</div>
                <div class="channel-meta">
                    <span class="channel-members"><i class="fas fa-users"></i> ${memberText}成员</span>
                    <span class="channel-activity">
                        <span class="activity-indicator"></span> 活跃中
                    </span>
                </div>
                ${buttonHTML}
            </div>
        `;

        container.appendChild(card);
    });
}

function addJoinButtonListeners() {
    document.querySelectorAll('.join-button').forEach(button => {
        button.addEventListener('click', async function() {
            const cId = this.dataset.cid;
            try {
                const response = await fetch(`${contextPath}/User/entryChannel`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded' // 修改为表单格式
                    },
                    body: `userId=${userId}&cId=${cId}` // 表单格式参数
                });

                const result = await response.text(); // 获取文本响应

                if (result === "success") {
                    alert("加入成功");
                    // 加入成功
                    document.getElementById("discover").click();
                } else {
                    // 加入失败
                    alert('加入频道失败: ' + (result || '未知错误'));
                }
            } catch (error) {
                console.error('加入频道失败:', error);
                alert('网络错误，请稍后重试');
            }
        });
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    renderRecommendedChannels();
    setupCategoryButtons();
    renderLoveChannels();
    // 初始加载射击游戏分类
    (async function init() {
        try {
            const response = await fetch(contextPath + '/User/findChannel?sort=射击游戏', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            const data = await response.json();
            renderSortChannels(data);
        } catch (error) {
            console.error('初始化分类频道失败:', error);
        }
    })();

    // 初始添加加入按钮监听
    addJoinButtonListeners();

    // 新增：搜索框Enter事件监听
    const searchInput = document.querySelector('.channel-search input');
    searchInput.addEventListener('keydown', async (e) => {
        if (e.key === 'Enter') {
            const keyword = searchInput.value.trim();
            if (keyword) {
                try {
                    const response = await fetch(
                        `${contextPath}/User/searchChannel?name=${encodeURIComponent(keyword)}`,
                        { method: 'POST', headers: { 'Content-Type': 'application/json' } }
                    );
                    searchChannel = await response.json();
                    if (!searchChannel || searchChannel.length === 0) {
                        alert("未查询到频道");
                    }
                    renderSearchChannels(searchChannel);
                } catch (error) {
                    console.error('搜索失败:', error);
                }
            }
        }
    });
});